<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/8/5
 * Time: 15:08
 */

namespace app\commi\controller;


use think\Controller;
use think\Request;

class Chouqian extends Controller
{
    public function index()
    {
        if(Request::instance()->isPost()) {
            $user_str = input('user');
            $chang_str = input('chang');
            // 人员数组
            $user = explode(',', $user_str);
            // 人数
            $user_num = count($user);
            // 场次名称
            $chang = explode(',', $chang_str);
            // 场次数量
            $num = count($chang);
        
            // 每组的人数
            $group_num = ceil($user_num / $num);
            $arr = []; // 放分组后的数组
            foreach($chang as $k => $v) {
                if(!empty($user)) {
                    for($i = 0; $i < $group_num; $i++) {
                        if(empty($user)) {
                            $arr[$v][$i] = '';
                        } else {
                            $count = count($user);
                            $rand1 = $count - 1;
                            $rand = rand(0, $rand1);
                            $arr[$v][$i] = $user[$rand];
                            unset($user[$rand]);
                            $user = array_values($user); // 将数组重新排列成索引数组
                        }
                    }
                }
            }
            foreach($arr as $kk => $vv){
                $value = array_filter($vv);
                if($value){
                    $arr[$kk] = implode(',', $value);
                }else{
                   $arr[$kk] = '';
                }
            }
            return json($arr);
        }
        return $this->fetch();
    }
    
    /**
     * 抽签
     * @return mixed
     */
    public function cq(){
        header("Access-Control-Allow-Origin:*");
        $team_name = input('team_name');
        $group_num = input('group_num');
        $user_num = input('user_num');
        if(empty($team_name)){
            return json(['code' => 100, 'msg' => '请填写参赛队']);
        }
        if(empty($group_num)){
            return json(['code' => 100, 'msg' => '请填写场次数量']);
        }
        if(empty($user_num)){
            return json(['code' => 100, 'msg' => '请填写每场队伍数']);
        }
        $team_arr = explode(',', $team_name);
        $list = [];
        foreach($team_arr as $k => $v){
            $list[$k]['id'] = $k + 1;
            $list[$k]['name'] = $v;
//            $list[$k]['tel'] = 1;
        }
        return json(['code' => 200, 'msg' => $list, 'groupNum' => $group_num, 'userNum' => $user_num]);
    }
}